package com.lovo.config;

import com.alibaba.fastjson.JSON;
import com.lovo.dao.MovieDao;
import com.lovo.dao.OrderDao;
import com.lovo.entity.MovieEntity;
import com.lovo.entity.OrderEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;

@Service
@ServerEndpoint("/socketService")
public class WebSocketService {

    private static OrderDao orderDao;

    @Autowired
    private void setOrderDao(OrderDao dao) {
        WebSocketService.orderDao = dao;
    }

    private static MovieDao movieDao;

    @Autowired
    private void setMovieDao(MovieDao dao) {
        WebSocketService.movieDao = dao;
    }

    @OnOpen
    public void open(Session session) throws IOException {
        session.getBasicRemote().sendText("与后台已经建立连接，，，，");
    }

    @OnMessage
    public void getMessage(String message, Session session) throws IOException, InterruptedException {
        System.out.println("前端发送回来的消息" + message);
        while (true) {
            List<OrderEntity> list = orderDao.selectList(null);
            for (int i = 0; i < list.size(); i++) {
                OrderEntity e = list.get(i);
                MovieEntity mo = movieDao.selectById(e.getMovieId());
                e.setMovieEntity(mo);
            }
            //往前端发送数据
            session.getBasicRemote().sendText(JSON.toJSONString(list));
            Thread.sleep(1000);
        }
    }
}
